﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Net;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
using System.Threading;
using System.Diagnostics;

namespace DDASProject.AutoUpdate
{
    class Program
    {
        
        static void Main(string[] args)
        {
           // Console.ReadLine();
            
            try
            {
                if (args.Length == 2)
                {
                    string descr = string.IsNullOrEmpty(args[1]) ? "没有描述" : args[1];
                    Console.WriteLine("---正在准备程序更新.....");
                    Console.WriteLine("更新内容:");
                    Console.WriteLine(args[1]);
                    Thread.Sleep(5000);
                    // Console.ReadLine(); //调试使用
                    Console.WriteLine("--------程序更新--------");
                    Console.WriteLine("开始更新,更新途中请不要关闭程序");
                    if (!Directory.Exists("temp"))
                    {
                        Directory.CreateDirectory("temp");
                    }

                    string fullPath = "temp";                   
                    //下载exe程序                        
                    string file = args[0];
                    Console.WriteLine(file);
                    Console.WriteLine("开始下载更新包.....");
                    HttpWebRequest Request1 = (HttpWebRequest)System.Net.WebRequest.Create(file);
                    HttpWebResponse Response1 = (HttpWebResponse)(WebResponse)Request1.GetResponse();
                    System.IO.BinaryReader sr1 = new BinaryReader(Response1.GetResponseStream());
                    long fileLenth1 = Response1.ContentLength;
                    byte[] content1 = sr1.ReadBytes((Int32)fileLenth1);
                    string fileName = Path.Combine(fullPath, Path.GetFileName(file));
                    FileStream so1 = new FileStream(fileName, FileMode.Create);
                    BinaryWriter fileWriter1 = new BinaryWriter(so1);
                    fileWriter1.Write(content1, 0, (Int32)fileLenth1);
                    fileWriter1.Close();
                    Console.WriteLine("下载完成...");
                    string currentDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName);
                    if (".zip" == Path.GetExtension(fileName).ToLower())
                    {
                        string errInfo;
                        Console.WriteLine("解压文件中...");
                        if (!UnZipFile(fileName, currentDir, out errInfo))
                        {
                            Console.WriteLine("解压文件失败!\r\n错误原因:{0}", errInfo);
                            LogError(new Exception("解压失败," + errInfo));
                            Thread.Sleep(3000);
                            return;
                        }
                        Console.WriteLine("解压完成...");
                    }
                    else
                    {
                        File.Copy(fileName, currentDir + Path.GetFileName(fileName), true);
                    }
                    File.Delete(fileName);//删除临时文件


                    //下载exe程序结束
                    Console.WriteLine("--------程序更新完成！--------");
                    Thread.Sleep(1000);
                    Process pross = System.Diagnostics.Process.Start("ProjectTest.exe", "");
                }
                else
                {
                    Console.WriteLine("更新错误,请联系资讯课");
                    string strInfo = string.Empty;
                    foreach (string s in args)
                    {
                        strInfo += s + "\r\n";
                    }
                    LogDebug(strInfo);
                    Thread.Sleep(3000);
                }
            }
            catch (System.Exception ex)
            {
                Console.WriteLine("--------更新失败,请与资讯课联系--------");
                Console.WriteLine("错误原因：" + ex.Message);
                LogError(ex);
            }
            finally
            {
                System.Diagnostics.Process.GetCurrentProcess().Kill();
            }
        }

        /// <summary>
        /// 发布异常信息。
        /// </summary>
        /// <param name="exception"></param>
        public static void LogError(Exception exception)
        {
            try
            {
                StringBuilder strInfo = new StringBuilder();
                strInfo.Append("\r\n---" + DateTime.Now.ToString() + "---\r\n");
                strInfo.Append("错误列表:\r\n");

                int exCount = 1;
                Exception currException = exception;
                do
                {
                    strInfo.Append(exCount + ") ");
                    strInfo.Append(currException.GetType().Name);
                    strInfo.Append("\r\n信息: ");
                    strInfo.Append(currException.Message);
                    strInfo.Append("\r\n");
                    exCount++;
                    currException = currException.InnerException;
                }
                while (currException != null);
                strInfo.Append("\r\n" + exception.StackTrace);

                string logFolder = "ErrorLog/";
                if (!Directory.Exists(logFolder))
                {
                    Directory.CreateDirectory(logFolder);
                }
                string logFile = Path.Combine(logFolder, DateTime.Now.ToString("yyyy-MM-dd") + "update.log");

                using (StreamWriter sw = new StreamWriter(logFile, true, Encoding.UTF8))
                {
                    sw.Write(strInfo.ToString());
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 记录调试信息
        /// </summary>
        /// <param name="msg"></param>
        public static void LogDebug(string msg)
        {
            try
            {
                string logFolder = "ErrorLog/";
                if (!Directory.Exists(logFolder))
                {
                    Directory.CreateDirectory(logFolder);
                }
                string logFile = Path.Combine(logFolder, DateTime.Now.ToString("yyyy-MM-dd") + "update.log");

                using (StreamWriter sw = new StreamWriter(logFile, true, Encoding.UTF8))
                {
                    sw.Write(msg);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #region  解压文件

        /// <summary>
        /// 功能：解压zip格式的文件。
        /// </summary>
        /// <param name="zipFilePath">压缩文件路径</param>
        /// <param name="unZipDir">解压文件存放路径,为空时默认与压缩文件同一级目录下，跟压缩文件同名的文件夹</param>
        /// <param name="err">出错信息</param>
        /// <returns>解压是否成功</returns>
        public static bool UnZipFile(string zipFilePath, string unZipDir, out string err)
        {
            err = "";
            if (zipFilePath == string.Empty)
            {
                err = "压缩文件不能为空！";
                return false;
            }
            if (!File.Exists(zipFilePath))
            {
                err = "压缩文件不存在！";
                return false;
            }
            // //解压文件夹为空时默认与压缩文件同一级目录下，跟压缩文件同名的文件夹
            //if (unZipDir == string.Empty)
            //     unZipDir = zipFilePath.Replace(Path.GetFileName(zipFilePath), Path.GetFileNameWithoutExtension(zipFilePath));
            // if (!unZipDir.EndsWith("\\"))
            //     unZipDir += "\\";
            if (!Directory.Exists(unZipDir))
                Directory.CreateDirectory(unZipDir);

            try
            {
                using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFilePath)))
                {

                    ZipEntry theEntry;
                    while ((theEntry = s.GetNextEntry()) != null)
                    {
                        string directoryName = Path.GetDirectoryName(theEntry.Name);
                        string fileName = Path.GetFileName(theEntry.Name);
                        if (directoryName.Length > 0)
                        {
                            Directory.CreateDirectory(unZipDir + directoryName);
                        }
                        string filePath = unZipDir + directoryName;
                        if (!filePath.EndsWith("\\"))
                            filePath += "\\";
                        if (fileName != String.Empty)
                        {
                            using (FileStream streamWriter = File.Create(filePath + theEntry.Name))
                            {

                                int size = 2048;
                                byte[] data = new byte[2048];
                                while (true)
                                {
                                    size = s.Read(data, 0, data.Length);
                                    if (size > 0)
                                    {
                                        streamWriter.Write(data, 0, size);
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                    }//while
                }
            }
            catch (Exception ex)
            {
                err = ex.Message;
                return false;
            }
            return true;
        }//解压结束

        public bool UnZipFile(Stream fileStream, string unZipDir, out string err)
        {
            err = "";
            try
            {
                using (ZipInputStream s = new ZipInputStream(fileStream))
                {

                    ZipEntry theEntry;
                    while ((theEntry = s.GetNextEntry()) != null)
                    {
                        string directoryName = Path.GetDirectoryName(theEntry.Name);
                        string fileName = Path.GetFileName(theEntry.Name);
                        if (directoryName.Length > 0)
                        {
                            Directory.CreateDirectory(unZipDir + directoryName);
                        }
                        if (!directoryName.EndsWith("\\"))
                            directoryName += "\\";
                        if (fileName != String.Empty)
                        {
                            using (FileStream streamWriter = File.Create(unZipDir + theEntry.Name))
                            {

                                int size = 2048;
                                byte[] data = new byte[2048];
                                while (true)
                                {
                                    size = s.Read(data, 0, data.Length);
                                    if (size > 0)
                                    {
                                        streamWriter.Write(data, 0, size);
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                    }//while
                }
            }
            catch (Exception ex)
            {
                err = ex.Message;
                return false;
            }
            return true;
        }
        #endregion
    }


}
